//
//  HSPublishTopicVC.m
//  HolyShit
//
//  Created by Robin on 2017/4/5.
//  Copyright © 2017年 HolyShit. All rights reserved.
//

#import "HSPublishTopicVC.h"

@interface HSPublishTopicVC ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (nonatomic, strong) UILabel *tagLb;
@property (nonatomic, strong) UITextField *titleTF;
@property (nonatomic, strong) UILabel *tipLb;
@property (nonatomic, strong) UITextView *contentTV;
@property (nonatomic, copy) NSString *tag;
@property (nonatomic, strong) UIImageView *picImgV;
@property (nonatomic, strong) UIImagePickerController *imagePicker;
@property (nonatomic, strong) UIImage *coverImg;

@end

@implementation HSPublishTopicVC

- (instancetype)initWithTag:(NSString *)tag
{
    if (self = [super init]) {
        _tag = tag;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self rightTitleWithTitle:@"发送" color:[UIColor yellowColor]];
    self.title = @"发布话题";
    self.view.backgroundColor = WHITE_COLOR;
    [self commonInit];
}

- (void)commonInit
{
    self.tagLb = [UILabel labelWithFrame:CGRectMake(10, 0, ScreenWidth - 10, 60) font:MYFont(Font34) color:HEXCOLOR(HSColorBlue) text:[NSString stringWithFormat:@"版块：%@", self.tag]];
    self.tagLb.textAlignment = NSTextAlignmentCenter;
    [self.tagLb showLineForDirection:MYDirectionBottom];
    [self.view addSubview:self.tagLb];
    
    self.titleTF = [[UITextField alloc] initWithFrame:CGRectMake(self.tagLb.left, self.tagLb.bottom, self.tagLb.width, self.tagLb.height)];
    self.titleTF.placeholder = @"标题，诱人的会有更多人看哦~";
    self.titleTF.font = MYFont(Font30);
    self.titleTF.textColor = HEXCOLOR(HSColorBlack);
    [self.titleTF showLineForDirection:MYDirectionBottom];
    [self.view addSubview:self.titleTF];
    
    self.tipLb = [UILabel labelWithFrame:CGRectMake(self.titleTF.left + 3, self.titleTF.bottom + 1, self.tagLb.width, 30) font:MYFont(Font30) color:HEXCOLOR(HSColorGray) text:@"内容，好内容可以获得更多的赞哦~"];
    [self.view addSubview:self.tipLb];
    
    self.contentTV = [[UITextView alloc] initWithFrame:CGRectMake(self.tagLb.left, self.titleTF.bottom, self.titleTF.width, ScreenHeight - NavBarHeight - self.titleTF.bottom - 150)];
    self.contentTV.font = MYFont(Font30);
    self.contentTV.textColor = HEXCOLOR(HSColorBlack);
    self.contentTV.backgroundColor = CLEAR_COLOR;
    [self.view addSubview:self.contentTV];
    
    self.picImgV = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"icon_home_camera"]];
    self.picImgV.frame = CGRectMake(self.tagLb.left, self.contentTV.bottom, 100, 100);
    self.picImgV.clipsToBounds = YES;
    self.picImgV.contentMode = UIViewContentModeCenter;
    self.picImgV.layer.borderColor = HEXCOLOR(HSColorGray).CGColor;
    self.picImgV.layer.borderWidth = 0.5;
    [self.view addSubview:self.picImgV];
    self.picImgV.userInteractionEnabled = YES;
    
    @weakify(self);
    [self.picImgV bk_whenTapped:^{
        [self takePhoto];
    }];
    
    [[self.contentTV rac_textSignal] subscribeNext:^(id x) {
        @strongify(self);
        self.tipLb.hidden = self.contentTV.text.length > 0;
    }];
}

- (void)rightButtonTouch
{
    if (![MYAppHelper shareHelper].hasNetWork) {
        return [UIWindow showFailedMsg:@"请检查网络"];
    }
    if (self.titleTF.text.length < 1) {
        return [UIWindow showWarnMsg:@"写个响亮的标题吧~"];
    }
    if (self.titleTF.text.length < 4 ||  self.titleTF.text.length > 30) {
        return [UIWindow showWarnMsg:@"标题要在4-30个字符之间哦~"];
    }
    if (self.contentTV.text.length < 20) {
        return [UIWindow showWarnMsg:@"内容太少啦"];
    }
    if (self.coverImg) {
        [self uploadImg];
    }
    else{
        [self uploadTopic];
    }
}

- (void)uploadImg
{
    [UIWindow showProgressWithMessage:@"正在上传图片..."];
    NSUInteger tag = arc4random() % 20;
    [[GCDQueue mainQueue] queueBlock:^{
        if (tag < 1) {
            [UIWindow showFailedMsg:@"上传失败，请重试"];
        }
        else{
            [self uploadTopic];
        }
    } afterDelay:2];
}

- (void)uploadTopic
{
    [UIWindow showProgressWithMessage:@"发帖中，请稍候...."];
    @weakify(self);
    [[GCDQueue mainQueue] queueBlock:^{
        [UIWindow showSuccessMsg:@"发帖成功，请等待小编审核"];
        [[GCDQueue mainQueue] queueBlock:^{
            @strongify(self);
            [self my_pop:YES];
        } afterDelay:HUD_DELAY_TIME];
    } afterDelay:1.5];
}

- (void)takePhoto
{
    [self.view endEditing:YES];
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *cancle = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alert addAction:cancle];
    @weakify(self);
    UIAlertAction *pic = [UIAlertAction actionWithTitle:@"选择照片" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        @strongify(self);
        if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]){
            [UIWindow showFailedMsg:@"不支持照片库，请查看权限"];
            return;
        }
        self.imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [self my_present:self.imagePicker];
    }];
    [alert addAction:pic];
    UIAlertAction *paizhao = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        @strongify(self);
        if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
            [UIWindow showFailedMsg:@"不支持相机，请查看权限"];
            return;
        }
        self.imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self my_present:self.imagePicker];
    }];
    [alert addAction:paizhao];
    [self presentViewController:alert animated:YES completion:nil];
}

#pragma mark - uiimagepicker delegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    // 判断获取类型：图片
    if ([mediaType isEqualToString:( NSString *)kUTTypeImage]){
        self.picImgV.contentMode = UIViewContentModeScaleAspectFill;
        // 判断，图片是否允许修改
        if ([picker allowsEditing]){
            //获取用户编辑之后的图像
            self.coverImg = [info objectForKey:UIImagePickerControllerEditedImage];
        } else {
            // 照片的元数据参数
            self.coverImg = [info objectForKey:UIImagePickerControllerOriginalImage];
        }
        self.picImgV.image = self.coverImg;
        // 如果是拍照，保存图片到相册中
        if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
            SEL selectorToCall = @selector(imageWasSavedSuccessfully:didFinishSavingWithError:contextInfo:);
            UIImageWriteToSavedPhotosAlbum(self.coverImg, self,selectorToCall, NULL);
        }
    }
    
    [picker dismissViewControllerAnimated:YES completion:^{
        
    }];
}

// 当用户取消时，调用该方法
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:^{
        
    }];
}

// 保存图片后到相册后，调用的相关方法，查看是否保存成功
- (void) imageWasSavedSuccessfully:(UIImage *)paramImage didFinishSavingWithError:(NSError *)paramError contextInfo:(void *)paramContextInfo{
    if (paramError == nil){
        NSLog(@"Image was saved successfully.");
    } else {
        NSLog(@"An error happened while saving the image.");
        NSLog(@"Error = %@", paramError);
    }
}

- (UIImagePickerController *)imagePicker
{
    if (!_imagePicker) {
        _imagePicker = [UIImagePickerController new];
        _imagePicker.navigationBar.tintColor = HEXCOLOR(appType);
        _imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
//        _imagePicker.allowsEditing = YES;
        _imagePicker.delegate = self;
    }
    return _imagePicker;
}

@end
